#!/bin/bash

# Flowable 流程部署脚本
# 用于批量部署所有 BPMN 流程文件

FLOWABLE_URL="${FLOWABLE_URL:-http://localhost:8081/flowable-rest}"
FLOWABLE_USER="${FLOWABLE_USER:-admin}"
FLOWABLE_PASS="${FLOWABLE_PASS:-test}"

PROCESSES_DIR="./flowable/processes"

echo "=========================================="
echo "Flowable 流程部署脚本"
echo "=========================================="
echo "Flowable URL: $FLOWABLE_URL"
echo "用户名: $FLOWABLE_USER"
echo "流程目录: $PROCESSES_DIR"
echo "=========================================="
echo ""

# 检查 Flowable 服务是否可用
echo "检查 Flowable 服务状态..."
if ! curl -s -u "$FLOWABLE_USER:$FLOWABLE_PASS" "$FLOWABLE_URL/service/management/engine" > /dev/null; then
    echo "错误: 无法连接到 Flowable 服务，请确保服务已启动"
    exit 1
fi
echo "Flowable 服务连接成功"
echo ""

# 部署所有 BPMN 文件
echo "开始部署流程..."
deployed=0
failed=0

for bpmn_file in "$PROCESSES_DIR"/*.bpmn20.xml; do
    if [ -f "$bpmn_file" ]; then
        filename=$(basename "$bpmn_file")
        echo "部署: $filename"
        
        response=$(curl -s -w "\n%{http_code}" -X POST \
            -u "$FLOWABLE_USER:$FLOWABLE_PASS" \
            -F "file=@$bpmn_file" \
            "$FLOWABLE_URL/service/repository/deployments")
        
        http_code=$(echo "$response" | tail -n1)
        body=$(echo "$response" | sed '$d')
        
        if [ "$http_code" = "201" ]; then
            echo "  ✓ 部署成功"
            deployed=$((deployed + 1))
        else
            echo "  ✗ 部署失败 (HTTP $http_code)"
            echo "  响应: $body"
            failed=$((failed + 1))
        fi
        echo ""
    fi
done

echo "=========================================="
echo "部署完成"
echo "成功: $deployed"
echo "失败: $failed"
echo "=========================================="

if [ $failed -gt 0 ]; then
    exit 1
fi

